package controllers

import (
	"encoding/json"
	"fmt"
	beego "github.com/beego/beego/v2/server/web"
	"github.com/jinzhu/gorm"
	"login/models"
)

type MainController struct {
	beego.Controller
}

type Res struct {
	Cre  int
	Msg  string
	Data interface{}
}
type AllRes struct {
	Cre     int
	Msg     string
	Data    interface{}
	AllPage int64
}

// 注册
func (c *MainController) Register() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	username := c.GetString("username")
	password := c.GetString("password")

	data := models.UserCc{
		Model:    gorm.Model{},
		Username: username,
		Password: password,
	}
	models.DB.Create(&data)
	c.Data["json"] = Res{200, "注册成功", data}
	c.ServeJSON(true)
}

func (c *MainController) List() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	name := c.GetString("name")
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 5)
	off := (page - 1) * size
	//从缓存中读取数据
	shop := models.RedisDB.Get("show" + name)
	var data []models.Products
	var count int64
	//判断缓存中是否有数据
	if shop.Val() != "" {
		fmt.Println("有数据")
		json.Unmarshal([]byte(shop.Val()), &data)
	} else {
		fmt.Println("无数据")
		models.DB.Debug().Offset(off).Limit(size).Where("name like ?", "%"+name+"%").Find(&data)
		models.DB.Model(&data).Where("name like ?", "%"+name+"%").Count(&count)
		marshal, _ := json.Marshal(&data)
		//写入数据
		models.RedisDB.Set("shop"+name, marshal, 0)
	}
	c.Data["json"] = AllRes{200, "查询列表成功", data, count}
	c.ServeJSON(true)
}

func (c *MainController) Add() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	name := c.GetString("name")
	price, _ := c.GetFloat("price")
	status := c.GetString("status")
	data := models.Products{
		Name:   name,
		Prince: price,
		Status: status,
	}
	models.DB.Create(&data)
	c.Data["json"] = Res{200, "添加成功", data}
	c.ServeJSON(true)
}

func (c *MainController) Del() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	id, _ := c.GetInt("id")
	data := models.Products{
		Model: gorm.Model{ID: uint(id)},
	}
	models.DB.Debug().Delete(&data)
	c.Data["json"] = Res{200, "删除成功", data}
	c.ServeJSON(true)
}

func (c *MainController) Show() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	id, _ := c.GetInt("id")
	data := models.Products{
		Model: gorm.Model{ID: uint(id)},
	}
	models.DB.Find(&data)
	c.Data["json"] = Res{200, "详情查询成功", data}
	c.ServeJSON(true)
}
